import GoEasy from 'goeasy';
import Vue from 'vue'
import store from '../store'
import { getMessage_count } from '@/static/js/news.js';
const _goEasy = GoEasy.getInstance({
	host: "hangzhou.goeasy.io", //若是新加坡区域：singapore.goeasy.io
	// appkey: "BC-2d04526a2e3843e1a155de771785533c",
	appkey: "BC-2d04526a2e3843e1a155de771785533c",
	modules: ['pubsub'] //根据需要，传入‘pubsub’或'im’，或数组方式同时传入
});
export function goEasy() {
	//建立连接
	_goEasy.connect({
		onSuccess: function () {
			console.log("GoEasy 连接成功");
			subscribeChannel(); //去订阅
		},
		onFailed: function (error) {
			//连接失败
			console.log('GoEasy 连接失败, code:' + error.code + ',error:' + error.content);
		}
	});
}
//goEasy订阅
function subscribeChannel() {
	let that = this;
	let userInfo = uni.getStorageSync('userInfo');
	if (!userInfo) return;
	_goEasy.pubsub.subscribe({
		channel: userInfo.id, //替换为您自己的channel
		onMessage: function (message) {
			//提交更新到vuex中
			store.commit('webSocketMessage', message);
			//收到消息
			console.log('webSocketMessage 注入vuex', store.state.webSocketMessage);
			if (JSON.parse(message.content) > 0) {
				console.log('执行if判断', JSON.parse(message.content));
				initNewMessage()
			}
		},
		onSuccess: function () {
			console.log('Channel订阅成功。');
		},
		onFailed: function (error) {
			console.log('Channel订阅失败, 错误编码：' + error.code + ' 错误信息：' + error.content);
		}
	});
}

//获取tabbar角标
async function initNewMessage() {
	let res = await getMessage_count({})
	if (res.code == 1) {
		let message = res.data
		let num = Number(message.comment) + Number(message.message) + Number(message.like) + Number(message
			.wendahuifu) + Number(message.dengnilaida)
		store.commit('set_wdNum', num)
	}
}